const fs = require('fs-extra');
const path = require('path');

const upload = async (ctx, next) => {
  if (ctx.request.files) {
    if (Math.random() < 0.04) {
      ctx.status = 404;
      return ctx.body = {
        status: 404,
        desc: "This is probability Error"
      }
    }
    const { file } = ctx.request.files;
    const file_size = 1024 * 1024;
    const { file_name, hash, size = file_size, hash_accept } = ctx.request.body;

    const file_name_list = file_name.split('.');
    file_name_list.pop();

    // 大文件切边保存
    if (size > 2 * file_size) {
      const chunkDir = path.join(__dirname, `../public/${hash_accept}_${file_name_list.join(".")}`);

      // 切片目录不存在，创建切片目录
      if (!fs.existsSync(chunkDir)) {
        await fs.mkdirs(chunkDir);
      }
      // 新建_重命名文件
      await fs.move(file.path, `${chunkDir}/${hash}`);
    } else {
      // 小文件直接保存
      const save_name = path.join(__dirname, `../target/${hash_accept}_${file_name}`);
      console.log(save_name)
      fs.move(file.path, save_name, (error) => {
        if (error) { ctx.body = error; }
      });
    }
    const callback = {
      status: 200,
      desc: "Success"
    };
    ctx.body = ctx.body ? ctx.body : callback;
  } else {
    ctx.body = {
      status: 404,
      desc: "This is Error"
    };
  }
}

module.exports = upload;